package main

import (
	"fmt"
	"math"
)

func main() {
	calculate(4.75/100/12, 240, 410000, 0)
}

func calculate(rates, rateMon, corpus float64, cType int) {
	limitTime := int(rateMon)
	//corpusLeft 还款之本金 corpusLeftMon还款之剩余本金
	timeLeft, corpusLeft, corpusLeftMon := rateMon, corpus, corpus
	var capMon, corpusMon, varerestMon, capTotle, corpusTotle, varerestTotle float64
	var rate = rates

	formatNumber := func(v float64) string {
		v = math.Round(v*100) / 100
		return fmt.Sprintf("%.2f", v)
	}

	calculateR := func() {
		for i := 1; i <= limitTime; i++ {
			var ratePow = math.Pow(rate+1, timeLeft)               //每期贷款利率
			capMon = (corpusLeft * rate * ratePow) / (ratePow - 1) //月供
			varerestMon = corpusLeftMon * rate                     //月供利息
			corpusMon = capMon - varerestMon                       //月供本金

			corpusLeftMon -= corpusMon   //本金余额
			capTotle += capMon           //还款总额
			varerestTotle += varerestMon //利息总额
			corpusTotle += corpusMon     //本金总额

			fmt.Printf("%d | %s | %s | %s | %s \n", i, formatNumber(capMon), formatNumber(varerestMon), formatNumber(corpusMon), formatNumber(corpusLeftMon))
		}
	}

	calculateC := func() {
		for i := 1; i <= limitTime; i++ {
			var ratePow = math.Pow(rate+1, timeLeft)               //每期贷款利率
			capMon = (corpusLeft * rate * ratePow) / (ratePow - 1) //月供
			varerestMon = corpusLeftMon * rate                     //月供利息
			corpusMon = capMon - varerestMon                       //月供本金

			corpusLeftMon -= corpusMon   //本金余额
			capTotle += capMon           //还款总额
			varerestTotle += varerestMon //利息总额
			corpusTotle += corpusMon     //本金总额

			fmt.Printf("%d | %s | %s | %s | %s \n", i, formatNumber(capMon), formatNumber(varerestMon), formatNumber(corpusMon), formatNumber(corpusLeftMon))
		}
	}
	if cType == 0 {
		calculateR()
	} else {
		calculateC()
	}

	fmt.Printf("还款总额 %s 本金总额 %s 利息总额 %s\n", formatNumber(capTotle), formatNumber(corpusTotle), formatNumber(varerestTotle))
}
